
# coding=utf-8

import hashlib
import binascii
import random
import Crypto #pip install pycryptodome
#D:\ProgramData\Anaconda3\Lib\site-packages，找到这个路径，下面有一个文件夹叫做crypto,将c改成C，
import Crypto.Random
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64

m = 'string123' #要签名的字符串
n = 10 #环签名的参与成员数量
k = hashlib.sha256(m.encode('utf-8')).hexdigest() #对称加密的秘钥
print(k)
v = random.randint(0, 1000) #随机选取的值
print(v)

# 公钥加密
def rsa_encode(message, public_key):
    # rsakey = RSA.importKey(public_key)  # 导入读取到的公钥
    cipher = PKCS1_v1_5.new(public_key)  # 生成对象
    # 通过生成的对象加密message明文，注意，在python3中加密的数据必须是bytes类型的数据，不能是str类型的数据
    cipher_text = base64.b64encode(
        cipher.encrypt(message.encode(encoding="utf-8")))
    # 公钥每次加密的结果不一样跟对数据的padding（填充）有关
    return cipher_text.decode()


# 公钥解密
def rsa_decode(cipher_text, private_key):
    # rsakey = RSA.importKey(private_key)  # 导入读取到的私钥
    cipher = PKCS1_v1_5.new(private_key)  # 生成对象
    # 将密文解密成明文，返回的是一个bytes类型数据，需要自己转换成str
    text = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
    return text.decode()

def test():
    message = "你好，世界！"
    cipher = rsa_encode(message, PublicKeys[0])
    print(cipher)
    msg = rsa_decode(cipher, PrivateKeys[0])
    print(msg)

    cipher = rsa_encode(message,PrivateKeys[0]) #这是私钥加密吗？
    print(cipher)
    msg = rsa_decode(cipher,  PrivateKeys[0]) #这是公钥解密吗？
    print(msg)

PrivateKeys = []  #环签名参与者的私钥
PublicKeys = []#环签名参与者的公钥
RandomNumbersX = []
RandomNumbersY = []
for i in range(0,n,1):
    _randnum = Crypto.Random.new().read
    _RsaPrivateKey = RSA.generate(1024, _randnum)
    PrivateKeys.append(_RsaPrivateKey)
    PublicKeys.append(_RsaPrivateKey.publickey())
    _x = random.randint(0,100)
    RandomNumbersX.append(_x)
    _y = cipher = rsa_encode(str(_x), _RsaPrivateKey)
    RandomNumbersY.append(_y)

for i in range(0,n,1):
    print(RandomNumbersX[i])
    print(RandomNumbersY[i])
    print(rsa_decode(RandomNumbersY[i],PrivateKeys[i]))